import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:go_router/go_router.dart';
import 'package:imath/models/article.dart';
import 'package:imath/models/question.dart';
import 'package:imath/models/user.dart';
import 'package:imath/pages/admin/admin_screen.dart';
import 'package:imath/pages/admin/camera_screen.dart';
import 'package:imath/pages/admin/pdf_uploader.dart';
import 'package:imath/pages/admin/test_functions.dart';
import 'package:imath/pages/article/article_add.dart';
import 'package:imath/pages/culture/mathematician_add.dart';
import 'package:imath/pages/article/article_viewer.dart';

import 'package:imath/pages/article/article_edit.dart';
import 'package:imath/pages/culture/mathematician_edit.dart';
import 'package:imath/pages/culture/experience_screen.dart';

import 'package:imath/pages/culture/mathematician_screen.dart';
import 'package:imath/pages/culture/problems_screen.dart';
import 'package:imath/pages/demo/pageview_demo.dart';
import 'package:imath/pages/home/book_listview.dart';
import 'package:imath/pages/home/home_screen.dart';
import 'package:imath/pages/home/news_detail.dart';
import 'package:imath/pages/home/splash_screen.dart';
import 'package:imath/pages/knowledge/add_knowledge.dart';
import 'package:imath/pages/knowledge/edit_knowledge.dart';
import 'package:imath/pages/knowledge/knowledge_detail.dart';
import 'package:imath/pages/knowledge/knowledge_listview.dart';

import 'package:imath/pages/paper/add_paper_screen.dart';
import 'package:imath/pages/question/add_question.dart';
import 'package:imath/pages/question/edit_question.dart';
import 'package:imath/pages/question/questions_main.dart';

import 'package:imath/pages/question/answer_viewer.dart';
import 'package:imath/pages/user/about_me.dart';
import 'package:imath/pages/user/avatar_edit.dart';
import 'package:imath/pages/user/help.dart';

import 'package:imath/pages/user/login.dart';
import 'package:imath/pages/user/pincode_input.dart';

import 'package:imath/pages/user/profile_screen.dart';
import 'package:imath/pages/user/feedback_screen.dart';
import 'package:imath/pages/user/register.dart';
import 'package:imath/pages/user/forgot_password.dart';
import 'package:imath/pages/user/reset_password.dart';
import 'package:imath/pages/user/change_password.dart';
import 'package:imath/pages/user/settings.dart';
import 'package:imath/pages/user/slider_captcha_client_verify.dart';
import 'package:flutter/foundation.dart';

final router = GoRouter(
  initialLocation: kIsWeb ? '/home' : '/splash',
  observers: [FlutterSmartDialog.observer],
  redirect: (context, state) {
    // 简化重定向逻辑，避免干扰正常跳转
    if (state.uri.toString() == '/') {
      return kIsWeb ? '/home' : '/splash';
    }
    return null;
  },
  routes: [
    // SplashScreen
    GoRoute(
      path: '/splash',
      builder: (context, state) => SplashScreen(),
    ),
    GoRoute(
      path: '/home',
      builder: (context, state) => HomeScreen(),
    ),
    GoRoute(
      path: '/knowledge',
      builder: (context, state) => KnowledgeListView(),
    ),
    GoRoute(
      path: '/mathematician',
      builder: (context, state) => MathematicianScreen(),
    ),

    GoRoute(
      path: '/article',
      builder: (context, state) {
        final article = state.extra as Article;
        return ArticleViewer(title: article.title, articleId: article.id);
      },
    ),
    GoRoute(
        path: '/knowdetail',
        builder: (context, state) {
          final knowledgeId = state.uri.queryParameters['knowledgeId'] ?? '0';
          return KnowledgeDetailScreen(knowledgeId: int.parse(knowledgeId));
        }),
    GoRoute(
      path: '/booklist',
      builder: (context, state) => BookListView(),
    ),
    GoRoute(
      path: '/experience',
      builder: (context, state) => ExperienceScreen(),
    ),
    GoRoute(
      path: '/problems',
      builder: (context, state) => ProblemsScreen(),
    ),
    //
    GoRoute(
      path: '/newsdetail',
      builder: (context, state) => NewsDetailPage(),
    ),

    GoRoute(
      path: '/questions',
      builder: (context, state) => const QuestionsMain(),
    ),
    GoRoute(
        path: '/profile',
        builder: (context, state) {
          return ProfileScreen();
        },
        routes: <RouteBase>[
          // Add child routes
          GoRoute(
            path: 'settings',
            builder: (context, state) => SettingsPage(),
          ),
          GoRoute(
            path: 'change-password',
            builder: (context, state) => ChangePasswordPage(),
          ),
          GoRoute(
            path: 'about',
            builder: (context, state) => AboutMePage(),
          ),
          GoRoute(
            path: 'help',
            builder: (context, state) => HelpPage(),
          ),
          GoRoute(
            path: 'avatarEdit',
            builder: (context, state) {
              final user = state.extra as User?;
              return AvatarEditScreen(
                currentAvatarBase64: user?.avatar,
              );
            },
          ),
          GoRoute(
            path: 'feedback',
            builder: (context, state) => const FeedbackScreen(),
          ),
        ]),

    // 用户登录管理相关
    GoRoute(
      path: '/login',
      builder: (context, state) => LoginPage(),
    ),
    GoRoute(
      path: '/register',
      builder: (context, state) => RegisterPage(),
    ),
    GoRoute(
      path: '/forgot-password',
      builder: (context, state) => ForgotPasswordPage(),
    ),
    GoRoute(
      path: '/reset-password',
      builder: (context, state) {
        final String? phone = state.uri.queryParameters['phone'];
        final String? verificationToken =
            state.uri.queryParameters['verification_token'];
        return ResetPasswordPage(
            phone: phone ?? '', verificationToken: verificationToken ?? '');
      },
    ),
    GoRoute(
      path: '/captcha',
      builder: (context, state) => SliderCaptchaClientVerify(
        title: '人机验证',
      ),
    ),
    GoRoute(
      path: '/verifycode',
      builder: (context, state) {
        final String? phone = state.uri.queryParameters['phone'];
        final String? password = state.uri.queryParameters['password'];
        final String? username = state.uri.queryParameters['username'];
        final bool? isRegister =
            state.uri.queryParameters['isRegister'] == 'true';
        final bool? isForgotPassword =
            state.uri.queryParameters['isForgotPassword'] == 'true';

        return PinputScreen(
          phone: phone ?? '',
          password: password ?? '',
          username: username,
          isRegister: isRegister,
          isForgotPassword: isForgotPassword,
        );
      },
    ),
    // 管理员入口
    GoRoute(
      path: '/admin',
      builder: (context, state) => AdminScreen(),
      routes: <RouteBase>[
        // Add child routes
        GoRoute(
          path: 'addmathematician',
          builder: (context, state) => AddMathematicianScreen(),
        ),
        GoRoute(
          path: 'addArticle',
          builder: (context, state) => AddArticlePage(),
        ),
        GoRoute(
          path: 'editArticle/:articleId',
          builder: (context, state) {
            final articleId = state.pathParameters['articleId'];
            return EditArticlePage(articleId: int.parse(articleId!));
          },
        ),
        GoRoute(
          path: 'addPaper',
          builder: (context, state) => AddPaperScreen(),
        ),

        GoRoute(
          path: 'addQuestion',
          builder: (context, state) => AddQuestionScreen(paperId: -1),
        ),
        GoRoute(
          path: 'editknow',
          builder: (context, state) {
            final knowledgeId = state.uri.queryParameters['knowledgeId'];
            return EditKnowledgeView(knowledgeId: int.parse(knowledgeId!));
          },
        ),
        GoRoute(
          path: 'editQuestion',
          builder: (context, state) {
            final questionId = state.uri.queryParameters['questionId'];
            return QuestionEditView(questionId: int.parse(questionId!));
          },
        ),
        GoRoute(
          path: 'viewAnswer',
          builder: (context, state) {
            final question = state.extra as Question;
            return AnswerViewer(question: question);
          },
        ),
        GoRoute(
          path: 'editMathematician',
          builder: (context, state) {
            final mathematicianId =
                state.uri.queryParameters['mathematicianId'];
            return EditMathematicianScreen(
                mathematicianId: int.parse(mathematicianId!));
          },
        ),
        GoRoute(
          path: 'addknow',
          builder: (context, state) => const AddKnowledgeView(),
        ),

        GoRoute(
          path: 'addByOCR',
          builder: (context, state) => const CameraScreen(),
        ),
        GoRoute(
          path: 'addByPDF',
          builder: (context, state) => PdfUploader(),
        ),
        // 测试页面
        GoRoute(
          path: 'test',
          builder: (context, state) => TestFunctionsPage(),
        ),

        //
      ],
    ),
    GoRoute(
      path: '/pageview',
      builder: (context, state) => PageViewDemo(),
    ),
  ],
);
